import {Component, Fragment} from 'react';
import {Form} from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {Modal, Input, DatePicker, Select, Spin, Button, message, Tooltip} from 'antd';
import PropTypes from 'prop-types';
import debounce from 'lodash/debounce';
import axios from 'axios';
import moment from 'moment-timezone';

import {fetchSelection} from '~/service/reports';

const {CancelToken} = axios;
const {Option} = Select;
let temp = null;
// 这个组件行课专用
class ModalSearchForm extends Component {
    static propTypes = {
        // eslint-disable-next-line react/forbid-prop-types
        data: PropTypes.array.isRequired,
        form: PropTypes.shape({
            resetFields: PropTypes.func,
            getFieldDecorator: PropTypes.func,
            setFieldsValue: PropTypes.func,
            getFieldValue: PropTypes.func,
            getFieldsValue: PropTypes.func,
            validateFields: PropTypes.func,
        }).isRequired,
    };

    constructor(props) {
        super(props);
        this.handleFetchSelection = debounce(this.handleFetchSelection, 500, {
            leading: true
        });
        this.selectCancelTokenSource = [];
        this.state = {
            options: [],
            dimensions: [],
            fetching: false,
        };
    }

    static getDerivedStateFromProps(props, state) {
        const {data} = props;
        if (!temp || temp.length === 0 || JSON.stringify(data) !== JSON.stringify(temp)) {
            temp = JSON.parse(JSON.stringify(data));
        }
        return {
            options: data,
        };
    }

    // 显示渲染
    getFields = () => {
        const {form} = this.props;
        const {options, dimensions, fetching} = this.state;
        const {getFieldDecorator} = form;
        return (
            options.map(item => {
                // 搜索选择框，行课专用所以不需要别的类型，因为行课添加比较 只有多选，单选，输入
                if (item.isinput === 0 || item.isinput === 3) {
                    return (
                        <Form.Item label={item.dimensionName} key={item.dimensionId}>
                            {getFieldDecorator(`${item.dimensionId}`, {
                                initialValue: item.filterItems,
                            })(
                                <Select
                                    mode={item.isinput === 0 ? 'multiple' : false}
                                    placeholder="展示50个选项，其余请搜索"
                                    notFoundContent={fetching ? <Spin size="small" /> : null}
                                    // eslint-disable-next-line react/jsx-no-bind
                                    onDropdownVisibleChange={this.handleFetchSelection.bind(this, item)}
                                    // eslint-disable-next-line react/jsx-no-bind
                                    onSelect={this.handleSelectOne.bind(this, item)}
                                    // eslint-disable-next-line react/jsx-no-bind
                                    onSearch={this.handleFetchSelection.bind(this, item)}
                                    allowClear showSearch
                                    filterOption={false}
                                    // eslint-disable-next-line react/jsx-no-bind
                                    getPopupContainer={triggerNode => triggerNode.parentNode}
                                >
                                    {item.isinput === 0 ? <Option key={0} value="全部">全部</Option> : null}
                                    {
                                        dimensions.map(i => (
                                            <Option key={i} value={i}>
                                                <Tooltip title={i} placement="topLeft">
                                                    {i}
                                                </Tooltip>
                                            </Option>
                                        ))
                                    }
                                </Select>
                            )}
                        </Form.Item>
                    );
                }
                return (
                    <Form.Item key={item.dimensionId} label={item.dimensionName}>
                        {getFieldDecorator(`${item.dimensionId}`, {
                            initialValue: item.filterItems[0] || '',
                        })(
                            <Input placeholder="输入查询关键词" allowClear />
                        )}
                    </Form.Item>
                );
            })
        );
    };

    // 勾选
    handleSelectOne = (item, e) => {
        const {form} = this.props;
        const {options} = this.state;
        const index = options.findIndex(i =>
            i.dimensionId === item.dimensionId && i.dimensionName === item.dimensionName);

        const selectValue = form.getFieldValue(`${item.dimensionId}`);
        if (e === '全部') {
            this.props.form.setFieldsValue({[`${item.dimensionId}`]: e});
        }
        else if (selectValue.indexOf('全部') > -1) {
            this.props.form.setFieldsValue({[`${item.dimensionId}`]: e});
        }
    };


    // 获取数据
    getSelectOption = params => {
        const source = CancelToken.source();
        this.selectCancelTokenSource.push(source);
        for (let i = 0; i < this.selectCancelTokenSource.length - 1; i++) {
            this.selectCancelTokenSource[i].cancel('请求取消');
        }
        fetchSelection(params, source.token)
            .then(res => {
                const {data} = res;
                this.setState({
                    dimensions: data,
                    fetching: false,
                });
            })
            .catch(() => {
                this.setState({
                    dimensions: [],
                    fetching: false,
                });
            });
    };

    // 获取维度列表(筛选项)
    handleFetchSelection = (item, e) => {
        const {dimensionId, taskId} = item;
        const {period, statisticsId} = this.props;
        const pager = {pageNum: 1, pageSize: 50};
        const searchKey = typeof e === 'string' ? e.trim() : '';
        let permissions = [];
        const pathSplit = window.location.pathname.split('/');
        const viewId = statisticsId || parseInt(pathSplit[pathSplit.length - 1], 10);
        this.props.form.validateFields((error, fieldsValue) => {
            if (error) {
                return;
            }
            // 查询日期 参数
            const dateKey = [];
            for (const key in fieldsValue) {
                if ((fieldsValue[key] instanceof Array) && (moment.isMoment(fieldsValue[key][0]))) {
                    const rangeValue = fieldsValue[key];
                    if (period === '小时') {
                        fieldsValue[key] = [rangeValue[0].format('YYYYMMDDHH'), rangeValue[1].format('YYYYMMDDHH')];
                    }
                    else if (period === '分') {
                        const format = 'YYYY-MM-DD HH:mm';
                        fieldsValue[key] = [rangeValue[0].format(format), rangeValue[1].format(format)];
                    }
                    else {
                        fieldsValue[key] = [rangeValue[0].format('YYYYMMDD'), rangeValue[1].format('YYYYMMDD')];
                    }
                }
                else if (typeof (fieldsValue[key]) === 'string') {
                    if (fieldsValue[key] === '') {
                        fieldsValue[key] = [];
                    }
                    else {
                        fieldsValue[key] = [fieldsValue[key]];
                    }
                }
                else if (!fieldsValue[key]) {
                    fieldsValue[key] = [];
                }
                else {
                    fieldsValue[key] = fieldsValue[key].filter(item => item !== '');
                }
            }
            const keys = Object.keys(fieldsValue);
            permissions = keys.map(item => {
                const permission = {};
                permission.dimensionId = item;
                permission.filterItems = fieldsValue[item] ? [fieldsValue[item]] : [];
                if (fieldsValue[item] instanceof Array) {
                    permission.filterItems = fieldsValue[item];
                }
                return permission;
            });
        });
        permissions = permissions.filter(item => item.filterItems.length > 0);
        if (e) {
            this.setState({fetching: true, dimensions: []});
            this.getSelectOption({dimensionId, viewId, taskId, pager, searchKey, permissions});
        }
    };

    render() {
        const {isVisiable, onOk, onCancel} = this.props;
        const layout = {
            labelCol: {
                span: 8,
            },
            wrapperCol: {
                span: 16,
            },
        };
        return (
            <Modal title="添加对比" visible={isVisiable} centered onOk={onOk} onCancel={onCancel}>
                <Form {...layout}>
                    {this.getFields()}
                </Form>
            </Modal>
        );
    }
}

const AddModalForm = Form.create({name: 'modalSearchForm'})(ModalSearchForm);

export default AddModalForm;
